﻿using AutoMapper;
using B.S.RbacData.Domain;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Write.API.Applications.Commands.RBAC;
using MediatR;

namespace B.S.RbacData.Write.API.Applications.Commandhandlters.RBAC
{
    /// <summary>
    /// 添加权限命令处理
    /// </summary>
    public class AddPermissionCommandHandlter : IRequestHandler<AddPermissionCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PermissionModel> permissionRep;
        private readonly IMapper mapper;

        public  AddPermissionCommandHandlter(IBaseRepository<PermissionModel> PermissionRep,IMapper mapper)
        {
            permissionRep = PermissionRep;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiResult<int>> Handle(AddPermissionCommand request, CancellationToken cancellationToken)
        {

            //判断是否存在权限名称
            var permissionnme= permissionRep.GetAll().FirstOrDefault(x => x.PermissionName == request.PermissionName&&!x.IsDeleted);
           
            if (permissionnme != null)
            {
                return new ApiResult<int>()
                {
                    code = ResultEnumCode.fails,
                    message = "权限名称已存在",
                    data = 0

                };

            }
            //添加权限
            var  permission=mapper.Map<PermissionModel>(request);
            permission.CreateTime= DateTime.Now;
            
            await permissionRep.AddAsync(permission);

            return new ApiResult<int>()
            {
                code = ResultEnumCode.Ok,
                message = "添加权限成功",
                data = 1

            };
        }
    }
}
